import React, { useState, useEffect } from "react";
import { PlusOutlined } from "@ant-design/icons";
import { Modal, Form, Input, Upload, message, Select, Image } from "antd";
import { putShops } from "../../services/shops";
import { useSelector, useDispatch } from "react-redux";
import { setupdate } from "../../store/slices/shopsSlice";
import { url } from "../../services";
import { findAll } from "../../services/type";
const { Option } = Select;

export default function UpdateFile({ show, shop }) {
    const [form] = Form.useForm(); //钩子函数绑定from表单 获取表单数据
    const [shopArr, setShopArr] = useState([]);
    // 有中间件 这里的student与studentSlice.js里面的student一样，那边改了这里也要改
    const { updateVisable, shops, aa } = useSelector((state) => state.shops);

    const [previewVisible, setPreviewVisible] = useState(false);
    const [previewImage, setPreviewImage] = useState("");
    const [previewTitle, setPreviewTitle] = useState("");

    // 新增和删除图片
    const [newImg, setNewImg] = useState([]);
    const [delImg, setDelImg] = useState([]);
    // 商品类型
    const [shopType, setShopType] = useState([]);
    const children = [];
    for (let i = 0; i < shopType.length; i++) {
        children.push(
            <Option key={shopType[i]._id} value={shopType[i]._id}>
                {shopType[i].typeName}
            </Option>
        );
    }
    // 一来就渲染分类数据
    let showModal = async () => {
        let data = await findAll();
        console.log(data.data, "type");
        setShopType(data.data);
    };
    useEffect(() => {
        showModal();
    }, [shopType.length]);
    form.setFieldsValue({ ...shops, typeName: shops.types._id });
    console.log(shops.shopImg, 'shopsasadadadddad');
    useEffect(() => {
        // 把内容渲染到对话框
        let array = shops.shopImg.map((item, i) => {
            return {
                uid: "-1",
                name: "image.png",
                status: "done",
                url: url + "/images/" + item,
            };
        });

        setFileList(array); //得到后端的图片
    }, [shops._id]);
    let dispatch = useDispatch();

    //  点击确认按钮
    const handleOk = async () => {
        let values = form.getFieldValue(); //获取对应字段（点击的内容）的值
        let arrrrrr = [];
        console.log(values, "abc");
        console.log(fileList, 'fileList');
        // setNewImg(
        fileList.map((item) => {
            if (item.url) {
                let jj = item.url.split('/')[3];
                arrrrrr.push(jj);
            } else {
                arrrrrr.push(item.response.filename);
            }
            console.log(arrrrrr, 'arrrrrr');
        })
        // )

        console.log(arrrrrr, 'newImgnewImgnewImg', delImg, 'delImgdelImgdelImgdelImg');
        // newImg.push(filename)

        await putShops({
            ...values,
            types: values.typeName.value,
            // isStatus: values.isStatus.label,
            isStatus: '已上架',
            shopImg:arrrrrr,
        });
        show();
        dispatch(setupdate(false));
    };

    const handleCancel = () => {
        dispatch(setupdate(false));
    };

    // 是否上架
    const handleUp = (e) => {
        console.log(e, "e");
        // console.log(`selected ${value}`);
    };
    const handleType = async () => { };


    const [fileList, setFileList] = useState([]);

    // 上传图片
    const getBase64 = (file) =>
        new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.readAsDataURL(file);

            reader.onload = () => resolve(reader.result);

            reader.onerror = (error) => reject(error);
        });
    // const handleCancel = () => setPreviewVisible(false);
    const handlePreview = async (file) => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj);
        }

        setPreviewImage(file.url || file.preview);
        setPreviewVisible(true);
        setPreviewTitle(
            file.name || file.url.substring(file.url.lastIndexOf("/") + 1)
        );
    };

    const handleChange = ({ fileList: newFileList }) => setFileList(newFileList);

    const handleRemove = (obj) => {
        console.log(obj, 'handleRemove');
        if (obj.url) {
            let jj = obj.url.split('/')[3];

            setDelImg([...delImg, jj]);
            console.log(jj, 'jjjjjj');
        } else {
            let gg = obj.response.filename;
            console.log(obj.response.filename, 'adakadkdlhlhaofa');
            setDelImg([...delImg, gg]);
        }
    }
    const uploadButton = (
        <div>
            <PlusOutlined />
            <div
                style={{
                    marginTop: 8,
                }}
            >
                上传图片
            </div>
        </div>
    );
    return (
        <>
            <Modal
                title="修改商品"
                visible={updateVisable}
                onOk={handleOk}
                onCancel={handleCancel}
                okText="确认"
                cancelText="取消"
            >
                <Form
                    name="updateForm"
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 18 }}
                    form={form}
                >
                    <Form.Item label="商品名" name="name">
                        <Input />
                    </Form.Item>

                    <Form.Item label="分类名" name="typeName">
                        <Select labelInValue onChange={handleType}>
                            {shopType.map((item, i) => (
                                <Option key={item} value={item._id}>
                                    {item.typeName}
                                </Option>
                            ))}
                        </Select>
                    </Form.Item>

                    <Form.Item name="price" label="价格">
                        <Input />
                    </Form.Item>
                    <Form.Item name="total" label="数量">
                        <Input />
                    </Form.Item>

                    <Form.Item name="isStatus" label="是否上架" onChange={handleUp}>
                        <Select labelInValue defaultValue={"hit"} style={{ width: 120 }}>
                            <Option value="hit">已上架</Option>
                            <Option value="down">已下架</Option>
                        </Select>
                    </Form.Item>
                    <Form.Item label="商品图片" name="shopImg">
                        <Upload
                            action={url + "/upload"}
                            listType="picture-card"
                            fileList={fileList}
                            onPreview={handlePreview}
                            onChange={handleChange}
                            onRemove={handleRemove}
                        >
                            {fileList.length >= 8 ? null : uploadButton}
                        </Upload>
                        <Modal
                            visible={previewVisible}
                            title={previewTitle}
                            footer={null}
                            onCancel={handleCancel}
                        >
                            <img
                                alt="example"
                                style={{
                                    width: "100%",
                                }}
                                src={previewImage}
                            />
                        </Modal>
                    </Form.Item>
                </Form>
            </Modal>
        </>
    );
}
